import {
    isType,
} from './../utils';

export default class Validator {
    constructor() {
        this.processingParams(...arguments);
    }
    // 处理参数
    processingParams(field, options) {
        let { validate, type, label } = options;
        if (validate === true) {
            validate = [{ message: `请${type === 'input' ? '输入' : '选择'}${label}` }];
        }
        if (isType(validate) === 'array') {
            validate.forEach(valid => {
                if (!valid.reg) valid.reg = /\S/;
            })
        }
        this.field = field;
        this.validate = validate;
    }
    // 验证
    verification(value) {
        if (isType(this.validate) === 'function') {
            return new Promise((...args) => {
                this.validate(value, (val) => this.verificationProcessing(...args, val));
            })
        }
        if (isType(this.validate) === 'array') {
            return new Promise((...args) => {
                const rules = this.validate;
                for (let i = 0, len = rules.length; i < len; i++) {
                    const rule = rules[i];
                    if (rule.reg.test(value) === false) {
                        this.verificationProcessing(...args, rule.message);
                        reject();
                        return;
                    }
                }
                this.verificationProcessing(...args);
            })
        }
    }
    // 验证处理
    verificationProcessing(resolve, reject, message = '') {
        message ? reject(message) : resolve();
        this.field.generateValidateWarn(message);
    }
}